package com.mixed;

import java.io.*;
import java.sql.*;

public class Mysql {

    static String Driver = "com.mysql.cj.jdbc.Driver";
    static String db_url = "jdbc:mysql://localhost:3306/RSA_PUBLIC_KEY";
    static String user = "root";
    static String password = "990814@Hwq";

    public static String readFile(String filepath) throws Exception {
        StringBuilder bs = new StringBuilder();
        String line = null;
        BufferedReader br = new BufferedReader(new FileReader(filepath));
        while((line = br.readLine()) != null) {
            bs.append(line);
        }
        br.close();
        return bs.toString();
    }

    public static void writeToMYSQL(String username, String publickey) {

        String sql = "replace into PUBLIC_KEY (USER, RSA_KEY) values ('" 
            + username + "', '" + publickey + "')";

        try{
            Class.forName(Driver);
            Connection conn = DriverManager.getConnection(db_url, user, password);
            Statement stmt = conn.createStatement();
            stmt.executeUpdate(sql);
            conn.close();
            stmt.close();
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }

    public static String readFromMYSQL(String username) throws Exception{
        String sql = "select RSA_KEY from PUBLIC_KEY where USER='" + username +"'";
        try{
            Class.forName(Driver);
            Connection conn = DriverManager.getConnection(db_url, user, password);
            Statement stmt = conn.createStatement();
            ResultSet re = stmt.executeQuery(sql);
            if(re.next() == false)
                return null;
            else
                return re.getString(1);
        }catch(Exception e){
            throw new Exception(e);
        }
    }

    /*public static void main(String[] args) throws Exception{
        String key = readFile("/home/mt11235/tmp/test/RSA/public_key.dat");
        writeToMYSQL(key, "hwqhwq");
        System.out.println(readFromMYSQL("hwqhwq"));
    }*/
}